package com.orangelife.mobile.individual.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.common.jump.HouseJumper;
import com.common.jump.PayJumper;
import com.common.sp.UserSp;
import com.common.util.CommonHttpBiz;
import com.curry.android.http.HttpUtil;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.address.activity.AddressListActivity;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.biz.Photo;
import com.orangelife.mobile.pay.biz.PayPwdHttpBiz;
import com.orangelife.mobile.pay.view.PayPwdDialog;
import com.thirdsdk.qiniu.QiniuService;
import com.thirdsdk.qiniu.QiniuService.QiniuListener;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.myhouse.biz.HouseBiz;
import com.orangelife.mobile.photo.Bimp;
import com.orangelife.mobile.photo.PhotoActivity;
import com.orangelife.mobile.widget.RoundImageViewByXfermode;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息
 *
 * @author lxj
 */

public class IndividualInformationActivity extends OrangeLifeBaseActivity {

    /** 个人中心的标题 */
    private TextView tvTitle;
    /** 个人信息的手机和昵称 */
    private TextView tvPhone, tvNickName, tvIdentity;
    /** 个人中心的RelativeLayout */
    private RelativeLayout rlPortrait;
    private RelativeLayout rlBindPhone;
    private RelativeLayout rlNickname;
    private RelativeLayout rlSetPassword;
    private RelativeLayout rlIdentity;
    private RelativeLayout rlAddress;
    /** 支付密碼 */
    private RelativeLayout rlPayPwd;
    private LinearLayout llMain;
    private TextView tvPayPwd;
    /** 登录按钮 */
    private Button btnLogin;
    /** 头像 */
    private RoundImageViewByXfermode rivHeadImage;
    /** 七牛服务器 */
    private QiniuService qiniuService;
    /** 设置监听器 */
    Photo photo = null;
    /** Activit 名称 **/
    final String MODULE_NAME = "/mine/perInfo";

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        CurryApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_individual_information);
        initeView();
        findView();
        qiniuService = new QiniuService();
        requestPayPwdStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        String phone = UserSp.getRegPhone();
        String nickname = UserSp.getNickname();
        if (!StringUtil.isContainBlank(phone)) {
            rlSetPassword.setVisibility(View.VISIBLE);
            tvPhone.setText(phone);
        } else {
            rlSetPassword.setVisibility(View.GONE);
        }
        if (!StringUtil.isContainBlank(nickname)) {
            tvNickName.setText(nickname);
        }
        btnLogin.setOnClickListener(listener);
        initHeadPhoto();
    }


    /** 初始化控件 */
    private void initeView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvPhone = (TextView) findViewById(R.id.tvIndividualPhone);
        tvNickName = (TextView) findViewById(R.id.tvIndividualNickname);
        rlPortrait = (RelativeLayout) findViewById(R.id.rlPortrait);
        rlBindPhone = (RelativeLayout) findViewById(R.id.rlBindPhone);
        rlNickname = (RelativeLayout) findViewById(R.id.rlNickname);
        rlSetPassword = (RelativeLayout) findViewById(R.id.rlSetPassword);
        rlIdentity = (RelativeLayout) findViewById(R.id.rlIdentity);
        rlAddress = (RelativeLayout) findViewById(R.id.rlAddress);
        rivHeadImage = (RoundImageViewByXfermode) findViewById(R.id.roundImageView);
        btnLogin = (Button) findViewById(R.id.btn_done);
        tvIdentity = (TextView) findViewById(R.id.tvIdentity);
        rlPayPwd = (RelativeLayout) findViewById(R.id.rlPayPwd);
        llMain = (LinearLayout) findViewById(R.id.llMain);
        tvPayPwd = (TextView) findViewById(R.id.tvPayPwd);
    }

    /** 为控件赋值或设置监听器 */
    private void findView() {
        tvTitle.setText("个人信息");
        rlBindPhone.setOnClickListener(listener);
        rlNickname.setOnClickListener(listener);
        rlSetPassword.setOnClickListener(listener);
        rlPortrait.setOnClickListener(listener);
        rlAddress.setOnClickListener(listener);
        rlIdentity.setOnClickListener(listener);
        tvIdentity.setText(HouseBiz.getCertInfo());
        rlPayPwd.setOnClickListener(listener);
    }


    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rlPayPwd:
                    clickPayPwd();
                    break;
                case R.id.rlPortrait:
                    Intent intent = new Intent(IndividualInformationActivity.this, PhotoActivity.class);
                    startActivityForResult(intent, 5);
                    break;
                case R.id.rlBindPhone:
                    IntentHelper.getInstances().getIntent(IndividualInformationActivity.this, ChangePhoneNum1Activity.class);
                    break;
                case R.id.rlNickname:
                    IntentHelper.getInstances().getIntent(IndividualInformationActivity.this, NickNameChange2Activity.class);
                    break;
                case R.id.rlSetPassword:
                    jumpToModPwd(false);
                    break;
                case R.id.rlAddress:
                    IntentHelper.getInstances().getIntent(IndividualInformationActivity.this, AddressListActivity.class);
                    break;
                case R.id.rlIdentity:
                    DataTrack.clickTrack(DataTrack.APP_NAME, MODULE_NAME, "myHouse");
                    if (UserSp.hasCert()) {
                        HouseJumper.jumpToList(IndividualInformationActivity.this);
                    } else {
                        HouseJumper.jumpToCert(IndividualInformationActivity.this, "false");
                    }
                    break;
                case R.id.btn_done:
                    CommonJumper.jumpToLoginWhenExitWithClear(IndividualInformationActivity.this);
                    finish();
                    break;
                case R.id.btn_take_photo:
                    photo.takePhoto();
                    break;
                case R.id.btn_pick_photo:
                    photo.openAlbum();
                    break;
                default:
                    break;
            }
        }
    };

    private void requestPayPwdStatus() {
        PayPwdHttpBiz.getPayPwdInfo(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                Map<String, Object> map = CommonHttpBiz.handleEntity(jsonObject, false);
                if (map != null) {
                    String statusCode = String.valueOf(map.get("stateCode"));
                    if (!"1".equals(statusCode)) {/*1未设置*/
                        hasSetPayPwd = true;
                    }
//                    statusInfo = String.valueOf(map.get("stateInfo"));
                    setPayPwdStatus();
                }
            }
        });
    }

    /** 是否已设置支付密码 */
    private void setPayPwdStatus() {
        if (!hasSetPayPwd) {/*未设置*/
            tvPayPwd.setText("未设置");
        } else {/*已设置*/
            tvPayPwd.setText("修改");
        }
    }

    /** 是否已设置密码 */
    private boolean hasSetPayPwd = false;

    /** 显示支付密码 */
    private void clickPayPwd() {
        /*如果已设置密码,则跳转到修改密码页;否则弹出密码设置框*/
        if (!hasSetPayPwd) {/*未设置,弹出设置框*/
            showPayPwd();
        } else {/*已设置,跳转到修改密码界面*/
            jumpToModPwd(true);
        }
    }

    /** 修改密码,true,支付密码,false,登录密码 */
    private void jumpToModPwd(boolean isPayPwd) {
        PayJumper.jumpToModPwd(this, isPayPwd);
    }

    private void showPayPwd() {
        PayPwdDialog ppd = new PayPwdDialog(this,true);
        ppd.setPayPwdBus(new PayPwdDialog.PayPwdBus() {
            @Override
            public void onEvent(int eventNum) {
                if (eventNum == 1) {
                    tvPayPwd.setText("修改");
                    hasSetPayPwd=true;
                }
            }
        });
        ppd.show();
        ppd.showKeyboard();
    }

    /**
     * 处理返回数据
     */
    private Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (!imgUrl.equals("")) {
                        UserSp.setProtraitImg(imgUrl);
                    }
                    closeDialog();
                    ToastHelper.getInstance()._toast(
                            IndividualInformationActivity.this.getResources().getString(
                                    R.string.uploading_head_photo_success));
                    initHeadPhoto();
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 重载返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 取头像图片
     */
    private void initHeadPhoto() {
        String url = UserSp.getProtraitImg();
        if (!"null".equals(url) && !"".equals(url)) {
            ImageDownloader.getImageDownloader().download(url, rivHeadImage,
                    ImageSize.IMAGE_SIZE_SMALL_PNG);
        } else {
            rivHeadImage.setBackgroundResource(R.drawable.icon_head);
        }
    }


    private String photoPath = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /* 拍照返回的图片 */
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                photoPath = data.getStringExtra("photoPath");
                setHeadImageAfterUpload();
                uploadHeadImage(photoPath);
                showDialog();
            }
        }
    }

    /**
     * 上传头像
     *
     * @param photoPath
     */
    private void uploadHeadImage(String photoPath) {
        qiniuService.headportraitUpload(photoPath, new QiniuListener() {
            @Override
            public void request(String fileNames) {
                if (fileNames.equals("500")) {
                    ToastHelper.getInstance()._toast("头像上传失败！");
                    return;
                } else {
                    imgUrl = fileNames;
                    uploadHeadImageUrl();
                }
            }
        });
    }

    /**
     * 上传头像后，不去网络下载，而是直接使用本地地址，设置圆形头像
     */
    private void setHeadImageAfterUpload() {
        if (photoPath != null && photoPath.equals("")) {
            return;
        }
        Bitmap bitmap = null;
        if (photoPath != null) {
            bitmap = Bimp.Compression(photoPath, 240, 240);
            rivHeadImage.setImageBitmap(bitmap);
        } else {
            rivHeadImage.setBackgroundResource(R.drawable.icon_head);
        }
    }

    private String imgUrl = "";

    /**
     * 上传头像到服务器
     */
    private void uploadHeadImageUrl() {
        String memberID = UserSp.getLoginID();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("memberID", memberID);
        map.put("protraitImg", imgUrl);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_UPLOAD_HEADIMAGE);
        rootMap.put("wat", 1);
        new JSONRequest(JSONRequest.PUT, rootMap, handler, HttpUtil.ACTION_JSON);
    }
}
